<template>
	<cmDialog v-model="dialogState" modal-title="参编单位" model-width="900px">
		<div style="padding: 20px 40px">
			<el-form ref="unitFormRef" :model="unitForm" :rules="unitRules" label-width="230px">
				<el-row style="display: none">
					<el-col :span="12">
						<el-form-item label="次序" prop="orderName">
							<el-input v-model="unitForm.orderName" type="number" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="单位名称" prop="editorUnitName">
							<el-input v-model="unitForm.editorUnitName" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系人" prop="contacts">
							<el-input v-model="unitForm.contacts" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="联系电话(手机)" prop="contactsTel">
							<el-input v-model="unitForm.contactsTel" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="联系人邮箱" prop="contactsEmail">
							<el-input v-model="unitForm.contactsEmail" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="联系地址" prop="contactsAddress">
							<el-input v-model="unitForm.contactsAddress" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="负责人" prop="responsiblePerson">
							<el-input v-model="unitForm.responsiblePerson" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="负责人电话(手机或座机)" prop="responsiblePersonTel">
							<el-input v-model="unitForm.responsiblePersonTel" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="负责人邮箱" prop="responsiblePersonEmail">
							<el-input v-model="unitForm.responsiblePersonEmail" placeholder="请输入" />
						</el-form-item>
					</el-col>
				</el-row>
				<el-row>
					<el-col :span="12">
						<el-form-item label="企业社会信用代码" prop="userCode">
							<el-input v-model="unitForm.userCode" placeholder="请输入" @input="handleCreditCodeInput" />
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="备注">
							<el-input v-model="unitForm.remark" placeholder="请输入" />
						</el-form-item>
					</el-col>
					<!-- <el-col :span="12">
                        <el-form-item label="单位类型" prop="unitType">
                            <el-select v-model="unitForm.unitType" placeholder="请选择">
                                <el-option v-for="item in unitTypeArr" :key="item.value" :label="item.label"
                                    :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col> -->
				</el-row>
			</el-form>
			<div class="dialog-foot">
				<el-button @click="handleAddCancel">取消</el-button>
				<el-button type="primary" @click="handleAddUnitFormSubmit(unitFormRef)">确定</el-button>
			</div>
		</div>
	</cmDialog>
</template>
<script lang="ts" setup>
import cmDialog from '@/components/cm-dialog/index.vue'
import { Unit } from '@/interface/declare'
import type { FormInstance, FormRules } from 'element-plus'
import { computed, reactive, ref, watch } from 'vue'

const props = defineProps({
	modelValue: Boolean,
	unitInfo: {
		type: Object as () => Unit,
		default: () => ({})
	},
	unitCount: {
		type: Number,
		default: 0
	}
})

const emit = defineEmits(['update:modelValue', 'submit-success', 'close-dialog'])

const dialogState = computed({
	get: () => props.modelValue,
	set: val => emit('update:modelValue', val)
})

const unitFormRef = ref<FormInstance>()
const unitForm = reactive<Unit>({
	orderName: 1,
	editorUnitName: '',
	contacts: '',
	contactsTel: '',
	contactsEmail: '',
	contactsAddress: '',
	responsiblePerson: '',
	responsiblePersonTel: '',
	responsiblePersonEmail: '',
	userCode: '',
	remark: '',
	unitType: 1,
	index: -1,
	isedit: true
})

const phoneOrLandlineValidator = (rule, value, callback) => {
	const phoneRegex = /^1[3-9]\d{9}$/
	const landlineRegex = /^(0\d{2,3})-?\d{7,8}$/

	if (!phoneRegex.test(value) && !landlineRegex.test(value)) {
		callback(new Error('请输入有效的手机号或座机号码'))
	} else {
		callback()
	}
}

const validateCreditCode = (rule: any, value: string, callback: (error?: Error) => void) => {
	if (!value) {
		callback(new Error('请输入社会信用代码'))
		return
	}

	// 1. 格式校验
	if (!/^[0-9A-Z]{18}$/.test(value)) {
		callback(new Error('必须为18位数字或大写字母'))
		return
	}
	callback()
}

const unitRules = reactive<FormRules>({
	orderName: [{ required: true, message: '请输入', trigger: 'blur' }],
	editorUnitName: [{ required: true, message: '请输入', trigger: 'blur' }],
	contacts: [{ required: true, message: '请输入', trigger: 'blur' }],
	userCode: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{ validator: validateCreditCode, trigger: 'blur' }
	],
	contactsTel: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{ pattern: /^1\d{10}$/, message: '请输入有效的手机号', trigger: 'blur' }
	],
	contactsEmail: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
			message: '请输入有效的邮箱地址',
			trigger: 'blur'
		}
	],
	contactsAddress: [{ required: true, message: '请输入', trigger: 'blur' }],
	responsiblePerson: [{ required: true, message: '请输入', trigger: 'blur' }],
	responsiblePersonTel: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{ validator: phoneOrLandlineValidator, trigger: 'blur' }
	],
	responsiblePersonEmail: [
		{ required: true, message: '请输入', trigger: 'blur' },
		{
			pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/,
			message: '请输入有效的邮箱地址',
			trigger: 'blur'
		}
	],
	remark: [{ required: true, message: '请输入', trigger: 'blur' }],
	unitType: [{ required: true, message: '请选择', trigger: 'change' }]
})
const unitTypeArr = [
	{
		label: '主编单位',
		value: 0
	},
	{
		label: '参编单位',
		value: 1
	}
]

const handleCreditCodeInput = (value: string) => {
	unitForm.userCode = value.toUpperCase()
}
const useTitle = ref<string>('')
watch(
	() => props.unitInfo,
	newVal => {
		console.log(newVal, '我是单位信息')
		const index = newVal.index ?? -1
		// unitForm.unitType = props.istype

		if (newVal && index > -1) {
			Object.assign(unitForm, newVal)
		}
	},
	{ immediate: true }
)

watch(
	() => props.unitCount,
	newVal => {
		if (newVal) {
			unitForm.orderName = newVal + 1
		}
	},
	{ immediate: true }
)

watch(
	() => dialogState.value,
	val => {
		if (val === false) {
			restForm()

			emit('close-dialog')
		}
	}
)

const handleAddCancel = () => {
	restForm()
	emit('close-dialog')
	emit('update:modelValue', false)
}

const restForm = () => {
	Object.assign(unitForm, { id: '' })
	Object.assign(unitForm, { orderName: 1 })
	Object.assign(unitForm, { editorUnitName: '' })
	Object.assign(unitForm, { contacts: '' })
	Object.assign(unitForm, { contactsTel: '' })
	Object.assign(unitForm, { contactsEmail: '' })
	Object.assign(unitForm, { contactsAddress: '' })
	Object.assign(unitForm, { responsiblePerson: '' })
	Object.assign(unitForm, { responsiblePersonTel: '' })
	Object.assign(unitForm, { responsiblePersonEmail: '' })
	Object.assign(unitForm, { remark: '' })
	Object.assign(unitForm, { unitType: 1 })
	Object.assign(unitForm, { userCode: '' })
	Object.assign(unitForm, { index: -1 })
	Object.assign(unitForm, { isedit: true })
}

const handleAddUnitFormSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) {
		return
	}
	await formEl.validate((valid, fields) => {
		if (valid) {
			const submittedData = { ...unitForm }

			///	console.log(submittedData, 'submittedData')
			emit('submit-success', submittedData)
			restForm()
		} else {
			console.log('error submit!', fields)
		}
	})
}
</script>
<style lang="scss" scoped>
.dialog-foot {
	display: flex;
	justify-content: center;
	padding-top: 20px;
	margin-bottom: 10px;
}
</style>
